package com.shanks.framework.mq.service.impl;

import com.shanks.framework.mq.enums.MQZone;
import com.shanks.framework.mq.exception.MQException;
import com.shanks.framework.mq.producer.BaseMQProducer;
import com.shanks.framework.mq.service.ProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ProducerServiceImpl implements ProducerService {

    public static Logger logger = LoggerFactory.getLogger(ProducerServiceImpl.class);
    private Map<String, BaseMQProducer> producerMap = new HashMap<>();

    /**
     * 默认生产者keY
     */
    @Value("${spring.application.name}")
    private String defalutProducerKey;

    @Value("${rocketmq.namesrvAddr}")
    private String basicZoneNamesrvAddr;

    @Value("${rocketmq.grayNamesrvAddr:null}")
    private String canaryZoneNamesrvAddr;


    @Override
    public void setDefaultProducer(BaseMQProducer mqProducer) {
        producerMap.put(defalutProducerKey, mqProducer);
    }

    @Override
    public void resgisterProducer(String producerKey, BaseMQProducer mqProducer) throws MQException {
        if (this.producerMap.get(producerKey) != null) {
            throw new MQException("producerKey already used: " + producerKey);
        }
        this.producerMap.put(producerKey, mqProducer);
    }

    @Override
    public BaseMQProducer getProducer(String producerKey) throws MQException {
        if (!producerMap.containsKey(producerKey)) {
            // 使用默认生产者发送
            producerKey = defalutProducerKey;
        }
        if (!producerMap.containsKey(producerKey)) {
            throw new MQException("producer not found: " + producerKey);
        }
        return producerMap.get(producerKey);
    }

    @Override
    public BaseMQProducer getProducerQuietly(String producerKey) {
        try {
            return this.getProducer(producerKey);
        } catch (MQException e) {
            logger.error("获取 Producer 失败. producerKey: {}", producerKey, e);
            return null;
        }
    }

    @Override
    public MQZone getZoneByProducerKeyQuietly(String producerKey) {
        BaseMQProducer producer = null;
        try {
            producer = getProducer(producerKey);
        } catch (MQException e) {
            logger.error("获取producer失败, producerKey:{}", producerKey, e);
            return null;
        }
        String namesrvAddr = producer.getNamesrvAddr();
        if (basicZoneNamesrvAddr.equals(namesrvAddr))
            return MQZone.BASIC;
        if (canaryZoneNamesrvAddr.equals(namesrvAddr))
            return MQZone.CANARY;
        return null;
    }
}
